package com.glsc.ngateway.platform.controller;

import com.glsc.ngateway.common.api.platform.dto.owncloud.OwnCloudDelParamDto;
import com.glsc.ngateway.common.api.platform.dto.owncloud.OwnCloudDownloadParamDto;
import com.glsc.ngateway.common.api.platform.dto.owncloud.OwnCloudQueryParamDto;
import com.glsc.ngateway.common.api.platform.dto.owncloud.OwnCloudRenameParamDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.utils.redis.IbltRedis;
import com.glsc.ngateway.common.base.utils.redis.RedisKey;
import com.glsc.ngateway.platform.service.owncloud.OwnCloudLog;
import com.glsc.ngateway.platform.service.owncloud.OwnCloudMethodEnum;
import com.glsc.ngateway.platform.service.owncloud.OwnCloudService;
import com.glsc.ngateway.platform.vo.SystemRelatedFileConfigVo;
import com.glsc.ngateway.platform.vo.SystemRelatedFileInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Objects;


/**
 * @author xuchang
 */
@RestController
@RequestMapping("/owncloud")
@Api(value = "网盘", tags = {"网盘"})
public class OwnCloudController {

    @Resource
    private OwnCloudService ownCloudService;

    @Resource
    private IbltRedis ibltRedis;

    @OwnCloudLog(OwnCloudMethodEnum.OWNCLOUD_METHOD_QUERY)
    @RequestMapping(method = RequestMethod.POST, value = "getRelatedFile")
    @ApiOperation(value = "查询系统关联文档", notes = "查询系统关联文档")
    public PlatformResponse<SystemRelatedFileInfoVo> getRelatedFile(@RequestBody OwnCloudQueryParamDto param) {
        return PlatformResponse.successData(ownCloudService.queryByName(param.getOpName(), param.getFileName()));
    }

    @OwnCloudLog(OwnCloudMethodEnum.OWNCLOUD_METHOD_DOWNLOAD)
    @RequestMapping(method = RequestMethod.POST, value = "download")
    @ApiOperation(value = "下载", notes = "下载")
    public ResponseEntity<byte[]> download(@RequestBody OwnCloudDownloadParamDto param, HttpServletRequest request) throws IOException {
        return ownCloudService.download(param.getUrl(), request, param.getIsDir());
    }

    /**
     * 新建目录或文件
     */
    @OwnCloudLog(OwnCloudMethodEnum.OWNCLOUD_METHOD_ADD)
    @RequestMapping(method = RequestMethod.POST, value = "addDirOrFile")
    @ApiOperation(value = "添加文件或文件夹", notes = "添加文件或文件夹")
    public PlatformResponse<String> addDirOrFile(@RequestPart(value = "url") String url, HttpServletRequest request, @RequestPart(value = "files", required = false) MultipartFile[] files) throws IOException {
        boolean addDirFlag = Objects.isNull(files) || files.length == 0;
        if (addDirFlag) {
            HttpResponse<String> httpResponse = ownCloudService.addDirOrFile(url, null);
            return HttpStatus.valueOf(httpResponse.statusCode()).is2xxSuccessful() ? PlatformResponse.successMsg("操作成功") : PlatformResponse.failedMsg("操作失败");
        } else {
            int suc = 0, failed = 0;
            for (MultipartFile file : files) {
                HttpResponse<String> httpResponse = ownCloudService.addDirOrFile(url, file);
                if (HttpStatus.valueOf(httpResponse.statusCode()).is2xxSuccessful()) {
                    suc++;
                } else {
                    failed++;
                }
            }
            return PlatformResponse.successMsg(failed == 0 ? "上传成功" : ("上传成功：" + suc + "个，失败：" + failed + "个"));
        }
    }

    /**
     * 重命名
     */
    @OwnCloudLog(OwnCloudMethodEnum.OWNCLOUD_METHOD_RENAME)
    @RequestMapping(method = RequestMethod.POST, value = "renameDirOrFile")
    @ApiOperation(value = "重命名文件或文件夹", notes = "重命名文件或文件夹")
    public PlatformResponse<?> renameDirOrFile(@RequestBody OwnCloudRenameParamDto param) throws UnsupportedEncodingException {
        HttpResponse<String> httpResponse = ownCloudService.renameDirOrFile(param.getUrl(), param.getNewUrl());
        return HttpStatus.valueOf(httpResponse.statusCode()).is2xxSuccessful() ? PlatformResponse.success() : PlatformResponse.failed();
    }

    /**
     * 删除
     */
    @OwnCloudLog(OwnCloudMethodEnum.OWNCLOUD_METHOD_DEL)
    @RequestMapping(method = RequestMethod.POST, value = "delDirOrFile")
    @ApiOperation(value = "删除文件或文件夹", notes = "删除文件或文件夹")
    public PlatformResponse<?> delDirOrFile(@RequestBody OwnCloudDelParamDto param) {
        HttpResponse<String> httpResponse = ownCloudService.delDirOrFile(param.getUrl());
        return HttpStatus.valueOf(httpResponse.statusCode()).is2xxSuccessful() ? PlatformResponse.success() : PlatformResponse.failed();
    }

    @RequestMapping(method = RequestMethod.GET, value = "config")
    @ApiOperation(value = "查看配置", notes = "查看配置")
    public PlatformResponse<SystemRelatedFileConfigVo> getConfig() {
        return PlatformResponse.successData(ownCloudService.getSystemDirConfig());
    }

    @OwnCloudLog(OwnCloudMethodEnum.OWNCLOUD_METHOD_UPDATE_CONFIG)
    @RequestMapping(method = RequestMethod.POST, value = "config")
    @ApiOperation(value = "设置配置", notes = "设置配置")
    public PlatformResponse<Void> updateConfig(@RequestBody List<SystemRelatedFileConfigVo.SystemRelatedFileConfigDetailVo> configList) {
        ownCloudService.updateSystemDirConfig(configList);
        return PlatformResponse.successMsg("操作成功");
    }

    @RequestMapping(method = RequestMethod.GET, value = "config/valid")
    @ApiOperation(value = "查看配置是否启动", notes = "查看配置是否启动")
    public PlatformResponse<Boolean> getValidConfig() {
        return PlatformResponse.successData(ownCloudService.getValidConfig());
    }

    @OwnCloudLog(OwnCloudMethodEnum.OWNCLOUD_METHOD_VALID_CONFIG)
    @RequestMapping(method = RequestMethod.POST, value = "config/{valid}")
    @ApiOperation(value = "设置配置启动", notes = "设置配置启动")
    public PlatformResponse<Void> validConfig(@PathVariable Boolean valid) {
        ownCloudService.validConfig(valid);
        return PlatformResponse.successMsg("操作成功");
    }

    @RequestMapping(method = RequestMethod.GET, value = "checkUnMatchDir")
    @ApiOperation(value = "查看未匹配目录的系统", notes = "查看未匹配目录的系统")
    public PlatformResponse<List<String>> checkUnMatchDir() {
        return PlatformResponse.successData(ownCloudService.checkUnMatchDir());
    }

    @OwnCloudLog(OwnCloudMethodEnum.OWNCLOUD_METHOD_SYNC_SYSTEM_DIR)
    @RequestMapping(method = RequestMethod.POST, value = "matchDir")
    @ApiOperation(value = "按配置生成系统目录", notes = "按配置生成系统目录")
    public PlatformResponse<Void> matchDir(@RequestBody List<String> systemList) {
        ownCloudService.matchDir(systemList);
        return PlatformResponse.successMsg("操作成功，请稍后查看");
    }

    @RequestMapping(method = RequestMethod.GET, value = "getMatchingProcessRate")
    @ApiOperation(value = "查看同步进度", notes = "查看同步进度")
    public PlatformResponse<String> getMatchingProcessRate() {
        return PlatformResponse.successData(ibltRedis.getValueByKey(RedisKey.GATEAY_OWNCLOUD_SYNC));
    }
}